import React, {Component} from 'react'
import {Card} from 'antd'
import {connect} from 'react-redux'
import '../../../less/index.less'
import {withRouter} from 'react-router-dom'
import TaskContent from './task-content-box'
import UrlPattern from 'url-pattern'
import * as taskActions from '../../../actions/task'
import FlipPages from './flip-pages'
import { FormattedMessage } from 'react-intl'

class TutorTask extends Component {
  constructor (props) {
    super(props)
    this.state = {
      taskId: 1,
      studentId: -1,
      programId: -1
    }
  }

  componentDidMount () {
    const pattern = new UrlPattern('/program/:programId/task/:taskId/student/:studentId')
    const urlParams = pattern.match(this.props.location.pathname) || {}
    const {taskId, studentId, programId} = urlParams
    this.setState({
      studentId,
      programId
    })
    this.props.getTaskInfo(taskId)
    this.props.getAssignments(taskId, studentId)
    this.props.getFlipTask(taskId)
  }

  flipTask (type) {
    const {flipIds, history} = this.props
    const {programId, studentId} = this.state
    const currentId = type === 'next' ? flipIds.nextId : flipIds.previousId
    this.props.getTaskInfo(currentId)
    this.props.getFlipTask(currentId)
    this.props.getAssignments(currentId, studentId)
    history.push(`/tutor/program/${programId}/task/${currentId}/student/${studentId}`)
  }

  render () {
    const {task} = this.props.taskInfo
    const taskSections = this.props.taskSections
    const link = <a target='_self' href={task.link}><FormattedMessage id='论坛答疑' /></a>
    const {flipIds} = this.props
    const {programId, studentId} = this.state

    return (
      <Card title={task.title} noHovering bordered={false} extra={task.link ? link : ''} key={task.Id}>
        <TaskContent taskInfo={this.props.taskInfo} taskSections={taskSections} isTutor programId={programId} studentId={studentId} />
        <FlipPages flipTask={this.flipTask.bind(this)} flipIds={flipIds} />
      </Card>
    )
  }
}

const mapStateToProps = state => ({
  taskInfo: state.taskInfo,
  taskSections: state.assignments,
  flipIds: state.flipPages
})
const mapDispatchToProps = dispatch => ({
  getTaskInfo: (taskId) => dispatch(taskActions.getTaskInfo(taskId)),
  getFlipTask: (taskId) => dispatch(taskActions.getFlipTask(taskId)),
  getAssignments: (taskId, studentId) => dispatch(taskActions.getAssignments(taskId, studentId))
})

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(TutorTask))
